<?php
/*
 * @Author: 杨红兵 
 * @Date: 2022-08-08 11:41:32 
 * @Last Modified by: 杨红兵
 * @Last Modified time: 2022-08-08 11:44:22
 */

namespace app\event\queue;

use app\event\deliver\KafakaQueue;
use think\facade\Log;
use think\facade\Queue;

abstract class AsyncJob extends SyncJob
{
    /**
     * 延迟执行时长
     * @var int
     */
    protected int $delay = 0;

    /**
     * 队列名称
     *
     * @var string
     * @Author YangHB
     * @DateTime 2022-08-08 13:42:40
     *
     */
    protected string $queue = 'default';

    /**
     * 设置队列名称
     *
     * @Author YangHB
     * @DateTime 2022-08-08 13:42:47
     *
     * @param string $tmpQueue
     * @return AsyncJob
     */
    public function setQueue(string $tmpQueue): AsyncJob
    {
        $this->queue = $tmpQueue;
        return $this;
    }

    /**
     * 是否是异步队列
     * @return bool
     */
    public function isAsyncQueue(): bool
    {
        return !empty($this->queue);
    }

    /**
     * 获取异步延迟时间
     * @return int
     */
    public function getDelay(): int
    {
        return $this->delay;
    }

    /**
     * 异步抛出任务
     *
     * @Author YangHB
     * @DateTime 2022-08-08 12:38:31
     *
     * @param $data
     * @param integer $delay
     * @return mixed
     */
    public function dispatch($data, int $delay = 0)
    {
        //异步任务最快5秒后执行
        $delay = $delay < 1 ? 1 : $delay;
        //异步任务，最大延时30天
        $delay = $delay > 86400 * 30 ? 86400 * 30 + rand(0, 3600) : $delay;

        /**
         * @var \think\Request
         */
        $request = app('request');

        $params['headers'] = [
            'Call_From' => 'queue_client',
        ];

        $params['raw'] = serialize($data['params']);
        $params['event'] = $data['event'];

        $params['base'] = [
            'app_type' => $request->param('app_type', ''),
            'app_guid' => $request->param('app_guid', ''),
        ];

        if ($this->queue === 'default') {
            $this->queue = 'default_' . env('APP_ENV', 'local');
        }

        // $res = Queue::later($delay, static::class, $params, $this->queue);
        $res = KafakaQueue::sendJob(static::class,$params,"test");
        // $res = Queue::push(static::class, $params, $this->queue);
        Log::info(
            __CLASS__ . '-' . __FUNCTION__.'异步任务,投递结果',
            compact('data', 'delay', 'res')
        );
        if ($res) {
            return true;
        }
        return false;
    }

}
